package exam.localdata;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/3/31 12:41
 * @since JDK 1.8
 *
 * 本地数据服务处理
 */
public class LocalDataServer {

    private static final String suffix=".data";

    private static final String devPATH=System.getProperty("user.dir");

    private static final String prodPATH="";

    private static final String dataPath="/localdata";


    /**
     *
     * @param name 文件名
     * @return 获取数据
     */
    public static Object getData(String name){
        String nameFile=devPATH+dataPath;
        FileInputStream fis=null;
        ObjectInputStream ois=null;
        File file = new File(nameFile+File.separator+"/"+name+suffix);
        if(!file.exists()){  //如果文件不存在，返回空数据
            System.out.println("文件存在吗");
            return null;
        }
        try {
            //反序列化
            fis= new FileInputStream(file);
            ois= new ObjectInputStream(fis);
            return ois.readObject();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                ois.close();
            }catch (IOException e2){
                e2.printStackTrace();
            }
        }
        return null;
    }

    /**
     *
     * @param name 文件名
     * @return 响应码
     */
    public static int storageData(String name,Map<String, Object> objectMap){
        String nameFile=devPATH+dataPath;
        FileOutputStream fos=null;
        ObjectOutputStream oos=null;
        try {
            File file=new File(nameFile+File.separator+"/"+name+suffix);
            fos = new FileOutputStream(file);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(objectMap);
            oos.flush();
            return 0;
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                oos.close();
            }catch (IOException e1){
                e1.printStackTrace();
            }
        }
        return -1;
    }


    /**
     * 获取本地数据路径
     * @return
     */
    public static List<String> getLocalFileList(){
        File file = new File(devPATH+dataPath);
        String[] file2=file.list();
        List<String> stringList=new ArrayList<>(file2.length);
        for (int i = 0; i < file2.length; i++) {
            stringList.add(file2[i]);
        }
        return stringList;
    }
}
